import config from './config'
import db from './database'

export default {
  config: config,
  db: db,
  vm: {},
  data: {},
  tickTime: 0,
  tickCount: 0,
  initTime: 0,
  lastLoopTime: 0,
  runTime: 0,
  lastScene: '',

  init(that) {
    this.initTime = this.lastLoopTime = new Date().getTime()

    this.tickTime = 1000 / this.config.fps

    this.vm = that

    this.db.init().then((response) => {
      this.data = response

      this.vm.$store.commit('updateGameData', this.data)
      
      setTimeout(() => { this.loop() }, this.tickTime)
    })
    // this.db.reset()
  },

  loop() {
    let currentTime = new Date().getTime()

    let timedelay = (currentTime - this.lastLoopTime) - (this.tickTime)

    if (timedelay > this.config.exceedDelay) {
      timedelay = 0
    }

    else {
      while (timedelay > (this.tickTime / 2)) {
        this.tick()
        timedelay -= this.tickTime
      }

      this.tick()

      this.render()

      this.lastLoopTime = currentTime - timedelay
    }

    setTimeout(() => { this.loop() }, this.tickTime - timedelay)
  },

  tick() {
    if (this.lastScene !== this.data.state.scene) {
      this.lastScene = this.data.state.scene

      switch (this.data.state.scene) {
        case 'main':
          this.vm.$store.commit('updateScene', 'play-main')
          break;
        case 'plot':
          this.vm.$store.commit('updateScene', 'play-plot')
          break;
      }
    }

    this.vm.$store.commit('incrementTickCount')
  },

  render() {
    this.vm.$store.commit('updateRunTime', this.tickTime)
  },
}